package com.party.refund.task;

import com.party.common.constant.Constant;
import com.party.core.model.crowdfund.Project;
import com.party.core.model.order.RefundPlan;
import com.party.core.service.crowdfund.IProjectService;
import com.party.core.service.order.IRefundPlanService;
import com.party.refund.biz.RefundPlanBizService;
import com.party.refund.biz.SupportBizService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 定时跑退款业务
 *
 * @Author: huangzequn
 * @Date: 2019/5/16 14:18
 */
@Component(value = "quartzRefund")
public class QuartzRefund {

    @Autowired
    private IRefundPlanService refundPlanService;

    @Autowired
    private IProjectService projectService;


    @Autowired
    private RefundPlanBizService refundPlanBizService;

    Logger logger = LoggerFactory.getLogger(getClass());

    //每天凌晨1点和下午1点执行
    @Scheduled(cron = "0 0 1,13 * * ?")
    public void runRefund() {
        logger.info("开始执行退款业务");
        List<String> list = SupportBizService.list;
        logger.info("list清除前数据：" + list.size());
        list.clear();//清除之前list中的余额不足的商户号
        logger.info("list清除后数据：" + list.size());
        long staTime = System.currentTimeMillis();
        RefundPlan refundPlan = new RefundPlan();
        refundPlan.setStatus("1");//需要把所有有效的数据查询出来
        refundPlan.setResult("0");//需要把没有执行过的数据查出来
        List<RefundPlan> refundPlanList = refundPlanService.list(refundPlan);
        logger.info("定时跑退款业务需要执行：" + refundPlanList.size() + "记录");
        try {
            for (RefundPlan plan : refundPlanList) {
                if (Constant.PROJECT.equals(plan.getType())) {
                    //众筹者下面所有的支持者退款
                    Project project = projectService.get(plan.getGoalId());
                    refundPlanBizService.refund(project);
                }
                if (Constant.SUPPORT.equals(plan.getType())) {
                    //单个支持者退款
                    refundPlanBizService.sendRefund(plan.getGoalId());
                }
                plan.setResult("1");//进队列了，就设置已经执行
                plan.setStatus("0");//设置这条记录为无效
                plan.setUpdateDate(new Date());
                refundPlanService.update(plan);
            }
        } catch (Exception e) {
            logger.error("定定时跑退款业务异常{}", e);
        }
        logger.info("开始执行退款业务结束，用时：" + (System.currentTimeMillis() - staTime));

    }
}
